package com.dstz.crm.core.manager.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dstz.base.api.exception.BusinessMessage;
import com.dstz.base.api.query.QueryFilter;
import com.dstz.base.api.query.QueryOP;
import com.dstz.base.core.util.StringUtil;
import com.dstz.base.manager.impl.BaseManager;
import com.dstz.crm.core.dao.CustomerDao;
import com.dstz.crm.core.dao.CustomerFollowupDao;
import com.dstz.crm.core.manager.CustomerManager;
import com.dstz.crm.core.manager.CustomerRelationManager;
import com.dstz.crm.core.model.Customer;
import com.dstz.crm.core.model.CustomerFollowup;
import com.dstz.crm.core.model.CustomerRelation;
import com.dstz.crm.core.model.Product;
import com.dstz.org.api.model.IUser;
import com.dstz.org.api.service.UserService;
import com.dstz.sys.api.model.IDataDict;
import com.dstz.sys.api.service.DataDictService;
import com.dstz.sys.util.ContextUtil;

import cn.hutool.core.collection.CollectionUtil;
/**
 * 案例 Manager处理实现类
 * @author aschs
 * @email aschs@qq.com
 * @time 2018-08-24 18:06:04
 */
@Service("customerManager")
public class CustomerManagerImpl extends BaseManager<String, Customer> implements CustomerManager{
	@Resource
	CustomerDao customerDao;
	@Resource
	CustomerFollowupDao customerFollowupDao;
	@Resource
	CustomerRelationManager customerRelationMananger;
	@Resource
	UserService userService;
	@Resource
	DataDictService dataDictService;
	 
	@Override
	public boolean isCustomerExist(Customer customer) {
		return customerDao.isCustomerExist(customer)>0;
	}
	
	@Override
	public List<Customer> query(QueryFilter queryFilter) {
		List<Customer> query = dao.query(queryFilter);
		if(query!=null&&query.size()>0) {
			getDataDictName(query);
		}
        return query;
    }
	
	@Override
	public Customer get(String entityId) {
		Customer customer =  super.get(entityId);
		if(customer!= null) {
			customer.setCustomerRelationList(customerRelationMananger.getCustomerRelation(entityId,"customerProduct"));
			String possesser = customer.getPossesser();
			if(StringUtil.isNotEmpty(possesser)) {
				List<IUser> userList=new ArrayList<>();
				IUser user = userService.getUserById(possesser);
				if(user!=null)
					userList.add(user);
				customer.setPossesserList(userList);
			}
			
		}
		return customer;
	}

	@Override
	public void saveCustomer(Customer customer) {
		if(StringUtil.isEmpty(customer.getId())) {
			customer.setType("1");
			customer.setPossesser(null);
			this.create(customer);
		}else {
//			if(customer.getPossesserList()==null||customer.getPossesserList().size()==0) {
//				throw new BusinessMessage("所有者不能为空!");
//			}
//			customer.setPossesser(customer.getPossesserList().get(0).getUserId());
			this.update(customer);
			customerRelationMananger.removeByCustomerId(customer.getId());
		}
		
		List<CustomerRelation> customerRelationList = customer.getCustomerRelationList();
		
		if(CollectionUtil.isEmpty(customerRelationList)) return;
		
		customerRelationList.forEach( rel ->{
			rel.setCustomerId(customer.getId());
			customerRelationMananger.create(rel);
		});
		 
	}

	@Override
	public List<Customer> queryShare(QueryFilter queryFilter) {
		List<Customer> query = customerDao.queryShare(queryFilter);
		if(query!=null&&query.size()>0) {
			getDataDictName(query);
		}
		return query;
	}

	private void getDataDictName(List<Customer> query) {
		List<IDataDict> khztList = dataDictService.getDictNodeList("khzt", false);
		List<IDataDict> khcsdList = dataDictService.getDictNodeList("khcsd", false);
		for (Customer customer : query) {
			String state = customer.getState();
			String maturity = customer.getMaturity();
			if(StringUtil.isNotEmpty(state)) {
				for (IDataDict iDataDict : khztList) {
					if(state.equals(iDataDict.getKey())) {
						customer.setStateName(iDataDict.getName());
						break;
					}
				}
			}
			if(StringUtil.isNotEmpty(maturity)) {
				for (IDataDict iDataDict : khcsdList) {
					if(maturity.equals(iDataDict.getKey())) {
						customer.setMaturityName(iDataDict.getName());
						break;
					}
				}
			}
		}
	}
	
	@Override
	public List<Customer> getMyUsableCustomers(QueryFilter queryFilter) {
		queryFilter.addParamsFilter("userId", ContextUtil.getCurrentUserId());
		List<Customer> myUsableCustomers=null;
		if(ContextUtil.isAdmin(ContextUtil.getCurrentUser())) {
			myUsableCustomers = customerDao.query(queryFilter);
		}else {
			myUsableCustomers = customerDao.getMyUsableCustomers(queryFilter);	
		}
		return myUsableCustomers;
	}
	@Override
	public List<Customer> getPublicCustomers(QueryFilter queryFilter) {
        queryFilter.addFilter("type_", 1, QueryOP.EQUAL);
		List<Customer> publicCustomers = customerDao.query(queryFilter);
		return publicCustomers;
	}

	@Override
	public void updateFollowup(String customerId) {
		
		CustomerFollowup latestOne = customerFollowupDao.getLatestOneByCustomerId(customerId);
		Integer countByCustomerId = customerFollowupDao.getCountByCustomerId(customerId);
		Customer customer=new Customer();
		customer.setId(customerId);
		customer.setLastFollowupTime(latestOne==null?null:latestOne.getFollowupTime());
		customer.setLastFollowupUserId(latestOne==null?null:latestOne.getCreateBy());
		customer.setFollowupNumber(countByCustomerId);
		customerDao.updateFollowup(customer);
	}

//	@Override
//	public Demo get(String entityId) {
//		Demo demo = super.get(entityId);
//		if(demo == null) return null;
//		
//		List<DemoSub> demoSublist = demoSubMananger.getByFk(entityId);
//		demo.setDemoSubList(demoSublist);
//		
//		return demo;
//	}
	
	
	

	/**
	 * URL 表单案例
	 */
//	@Override
//	public void saveDemoJson(ActionCmd actionCmd) {
//		String bizKey = actionCmd.getBusinessKey();
//		JSONObject object = actionCmd.getBusData();
//		Product demo = JSON.toJavaObject(object, Product.class);
//		
//		if(StringUtil.isEmpty(bizKey)) {
//			String id = IdUtil.getSuid();
//			actionCmd.setBusinessKey(id);
//			demo.setId(id);
//			productDao.create(demo);
//			
//			Map<String,Object> hashMap = new HashMap<>();
//			hashMap.put("startVariable", demo.getName());
//			//启动时候设置一些流程变量，请看 act_ru_variable 表、在整个流程声明周期您都可以使用该流程变量，可以用于分支判断等等
//			actionCmd.setActionVariables(hashMap);
//		}else {
//			productDao.update(demo);
//			Map<String,Object> hashMap = new HashMap<>();
//			hashMap.put("doTaskVariable", demo.getName() + "-" + actionCmd.getActionName());
//			actionCmd.setActionVariables(hashMap);
//		}
//	}
	
}
